import router from "@/router";
import vuex from "@/store";
import axios, { AxiosResponse } from "axios";
import ElementUI from "element-ui";

let http = axios.create({
    baseURL:"/api/"
});

// 自动携带Authorization
http.interceptors.request.use((req)=>{
    if(req.headers && vuex.state.token){
        req.headers["Authorization"] = "Bearer " + vuex.state.token;
    }
    return req;
})

// 处理登录错误的情况
http.interceptors.response.use((res)=>{
    if(res.status >= 400){
        ElementUI.Message.error("服务器异常，未返回正常的数据");
    }
    if(res.data.code == 403){
        ElementUI.Message.error("登录鉴权无效，请尝试重新登录");
        router.push("/login");
        vuex.commit("logout");
    }
    return res;
})


export interface ResourcesEditResult {
    // 添加
    add<T = any, R = AxiosResponse<T>, D = any>(data : any) : Promise<R>;
    // 编辑
    edit<T = any, R = AxiosResponse<T>, D = any>(id: number, data: any) : Promise<R>;
    // 删除
    delete<T = any, R = AxiosResponse<T>, D = any>(id : number) : Promise<R>;
    // 查询
    get<T = any, R = AxiosResponse<T>, D = any>(params? : any) : Promise<R>;
}

/**
 * 资源操作
 * @param controllerName 控制器的名称
 * @returns 
 */
export function ResourcesEdit(controllerName : string) : ResourcesEditResult {
    let res : ResourcesEditResult = {
        add: function <T = any, R = AxiosResponse<T, any>, D = any>(data: any): Promise<R> {
            return http.post(controllerName,data);
        },
        edit: function <T = any, R = AxiosResponse<T, any>, D = any>(id: number, data: any): Promise<R> {
            return http.put(controllerName,{
                id,
                data
            });
        },
        delete: function <T = any, R = AxiosResponse<T, any>, D = any>(id: number): Promise<R> {
            let data : any = {
                id
            }
            return http.delete(controllerName,{
                data
            })
        },
        get: function <T = any, R = AxiosResponse<T, any>, D = any>(params? : any): Promise<R> {
            let url = controllerName;
            if(params){
                url += "?"+params;
            }
            return http.get(url);
        }
    }
    return res;
}

/**
 * 获取数据数量
 */
export function getCounts(){
    return http.get("/counts");
}

/**
 * 登录
 * @param username 用户名
 * @param password 密码
 * @returns 
 */
export function login(username : string,password : string){
    return http.post("/login",{
        username: username,
        password: password
    })
}

/**
 * 获取type对应的数量列表
 * @param type 
 * @returns 
 */
export function getCountAllFromType(type : 1 | 2){
    return http.post("/count_all_from_type",{
        type
    })
}